package com.dragon.modules.yuegou.client.wechat_mini.service.impl;

import com.dragon.modules.yuegou.client.wechat_mini.client.SecurityClient;
import com.dragon.modules.yuegou.client.wechat_mini.common.MiniBusinessException;
import com.dragon.modules.yuegou.client.wechat_mini.common.MiniCode;
import com.dragon.modules.yuegou.client.wechat_mini.request.MediaCheckAsyncRequest;
import com.dragon.modules.yuegou.client.wechat_mini.response.MediaCheckAsyncResponse;
import com.dragon.modules.yuegou.client.wechat_mini.security.AccessTokenService;
import com.dragon.modules.yuegou.client.wechat_mini.service.SecurityService;
import com.dragon.modules.yuegou.web.Check;

import java.io.File;

/**
 * 构造一个内容安全服务实现类
 * 
 * @author liuwu
 *
 */
public class SecurityServiceImpl implements SecurityService {

	/**
	 * 客户端
	 */
	private final SecurityClient client;

	/**
	 * 凭证服务
	 */
	private final AccessTokenService tokenService;

	/**
	 * 构造一个内容安全服务
	 * 
	 * @param client       认证接口客户端
	 * @param tokenService 凭证服务
	 */
	public SecurityServiceImpl(SecurityClient client, AccessTokenService tokenService) {
		super();
		Check.notNull(client, "client is required");
		Check.notNull(tokenService, "tokenService is required");
		this.client = client;
		this.tokenService = tokenService;
	}

	@Override
	public boolean imgSecCheck(File file) {
		try {
			tokenService.executeAutoRetry(accessToken -> client.imgSecCheck(accessToken, file));
		} catch (MiniBusinessException e) {
			if (e.is(MiniCode.RISKY_CONTENT)) {
				return false;
			}
			throw e;
		}
		return true;
	}

	@Override
	public String imageCheckAsync(String mediaUrl) {
		MediaCheckAsyncRequest request = new MediaCheckAsyncRequest();
		request.setMediaType(2);
		request.setMediaUrl(mediaUrl);
		return tokenService.executeAutoRetry(accessToken -> client.mediaCheckAsync(accessToken, request),
				MediaCheckAsyncResponse::getTraceId);
	}

	@Override
	public String voiceCheckAsync(String mediaUrl) {
		MediaCheckAsyncRequest request = new MediaCheckAsyncRequest();
		request.setMediaType(1);
		request.setMediaUrl(mediaUrl);
		return tokenService.executeAutoRetry(accessToken -> client.mediaCheckAsync(accessToken, request),
				MediaCheckAsyncResponse::getTraceId);
	}

	@Override
	public boolean msgSecCheck(String content) {
		try {
			tokenService.executeAutoRetry(accessToken -> client.msgSecCheck(accessToken, content));
		} catch (MiniBusinessException e) {
			if (e.is(MiniCode.RISKY_CONTENT)) {
				return false;
			}
			throw e;
		}
		return true;
	}

}
